package com.softeem.musicserver.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.musicserver.dto.MusicDetails;
import com.softeem.musicserver.dto.R;
import com.softeem.musicserver.entity.Ablum;
import com.softeem.musicserver.entity.Music;
import com.softeem.musicserver.entity.Singer;
import com.softeem.musicserver.service.AblumService;
import com.softeem.musicserver.service.MusicService;
import com.softeem.musicserver.service.SingerService;
import com.softeem.musicserver.utils.QiniuOssUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@Tag(name="音乐管理",description = "包含音乐资源上传，列表查询，信息更新，删除下架操作等")
@RestController
public class MusicController {

    @Autowired
    private MusicService musicService;
    @Autowired
    private AblumService ablumService;
    @Autowired
    private SingerService singerService;

    @Operation(summary = "音乐资源列表",description = "分页查询所有音乐资源，根据当前页(page)和每页记录数(limit)查询")
    @Parameters({
            @Parameter(name = "page",description = "当前查询页码"),
            @Parameter(name = "limit",description = "每页数据条数")
    })
    @GetMapping("/music/list")
    public R list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        //声明临时变量存储歌曲详情数据（歌曲，专辑，歌手）
        List<MusicDetails> details = new ArrayList<>();
        //执行分页查询
        List<Music> list = musicService.list(new Page<Music>(page, limit));
        list.forEach(m->{
            //获取歌曲专辑id
            Integer aid = m.getAid();
            Ablum ablum = ablumService.getById(aid);
            //获取歌手id
            Integer sid = ablum.getSid();
            Singer singer = singerService.getById(sid);
            //创建歌曲详情对象
            MusicDetails md = new MusicDetails();
            md.setId(m.getId());
            md.setName(m.getName());
            md.setUrl(m.getPath());
            md.setStyle(m.getStyle());
            md.setSize(m.getSize());
            md.setDuration(m.getDuration());

            md.setAblumImg(ablum.getCoverimg());
            md.setAblumName(ablum.getName());
            md.setReleaseDate(ablum.getReleasedate());

            md.setSingerName(singer.getName());

            //将对象存入集合
            details.add(md);
        });
        //获取总数据行数
        long count = musicService.count();
        return R.ok().setMsg("查询成功").setData(details).setCount(count);
    }


    @Operation(summary = "音乐上传",description = "上传音乐信息以及文件对象")
    @Parameters({
            @Parameter(name = "music",description = "音乐资源文本信息，名称，专辑，流派，歌词等"),
            @Parameter(name = "myfile",description = "上传的音乐文件对象")
    })
    @PostMapping("/music/upload")
    public R upload(Music music, MultipartFile myfile) throws IOException {
        //获取文件名称
        String fname = myfile.getOriginalFilename();
        //文件大小
        long size = myfile.getSize();
        //获取文件对象输入流
        InputStream is = myfile.getInputStream();

        //获取key（当前文件的唯一标识）
        String key = UUID.randomUUID().toString();
        //创建七牛云工具对象
        QiniuOssUtils utils = new QiniuOssUtils();
        //执行上传，获取云端服务器返回的文件地址
        String path = utils.upload(is, key);

        music.setPath(path);
        music.setSize((int)size);

        //执行添加
        boolean b = musicService.save(music);
        if(b){
            return R.ok().setData(music).setMsg("上传成功");
        }
        //失败时从云存储中同时删除文件
        utils.delete(key);
        return R.fail().setMsg("上传失败");
    }
}
